//
//  HomeViewController.m
//  copyrightTrading
//
//  Created by 郭子一 on 2020/10/5.
//  Copyright © 2020 郭子一. All rights reserved.
//

#import "HomeViewController1.h"
#import "PopView.h"
#import "HomeRecommandViewController.h"
#import "HomeCategoryViewController.h"
#import <CommonCrypto/CommonCryptor.h>
@interface HomeViewController1 ()

@property (nonatomic, strong)  NSArray *menuList;
@property (nonatomic, strong) NSArray *commendList; // 推荐列表
@property (nonatomic, strong) NSArray *yingxiangList; // 影像馆
@property (nonatomic, strong) NSArray *vipList; // VIP下载专区
@end

@implementation HomeViewController1

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    PopView *popView = [[PopView alloc] initWithStyle:KFaceType];
//    popView.delegate = self;
    
    [self setupUI];
//    [self requestData];
    [self observeNetWork];
    NSString *dfdf = [self currentTimeStr];
    
    /**
     source: web    来源
     time:   十三位时间戳
     app-type: ios/android
     did: 设备号
     version: 版本号(1)
     model: 手机型号（iPhone 12）
     */
    NSString *paramString = @"app-type=ios&did=10086&model=iPhone12&source=app&time=1602468542006&version=1.0";
    NSString *dfddf = [self encryptUseDES:paramString key:@"436576kfi786ghj4"];
}

/**
 加密方法
 plainText 加密明文
 key 加密密钥
 */
- (NSString *)encryptUseDES:(NSString *)plainText key:(NSString *)key
{
      NSMutableString *ciphertext = [NSMutableString new];//用于拼接加密后的字符串
      NSData * encryptData =[plainText dataUsingEncoding:NSUTF8StringEncoding];//明文转二进制
      const char *encryptBytes = (const char *)[encryptData bytes];//转字符
      size_t encryptDataLength = [encryptData length];//获取字符长度
      NSData * keyData =[key dataUsingEncoding:NSUTF8StringEncoding];//密钥转二进制
      const char *keyBytes = (const char *)[keyData bytes];//密钥转字符
      //size_t keyDataLength = [keyData length];//获取密钥长度(默认kCCKeySizeDES 8位，你也可以传入自己获取的长度，前提你的key只能写前八位)
      NSString * iv = [key substringWithRange:NSMakeRange(0, 8)];//获取8位随机数向量
      NSData * ivData =[iv dataUsingEncoding:NSUTF8StringEncoding];//向量转二进制
      const char *ivBytes = (const char *)[ivData bytes];//向量转字符
      unsigned char buffer[1024 *15];//加密缓存大小 自己写的15k大小 1k 1024b 容纳512个汉子
      memset(buffer, 0, sizeof(char));//给缓存区开辟内存空间
      size_t numBytesEncrypted = 0;//用来表示长度
      CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,//加密，加密类型DES
                                      kCCOptionPKCS7Padding,//在JAVA中使用这种方式加密："DES/CBC/PKCS5Padding" 对应的OC的是 kCCOptionPKCS7Padding.
                                      keyBytes, kCCKeySizeDES,//密钥字符数据，密钥字符长度
                                      ivBytes,//向量字符数据
                                      encryptBytes, encryptDataLength,//明文字符数据，明文字符长度
                                      buffer, 1024 *15,//缓存buffer，缓存buffer长度
                                      &numBytesEncrypted);//获取加密后的字符长度
      if (cryptStatus == kCCSuccess)//加密成功
      {
            NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];//获取加密后的二进制数据
//            NSString * one =[self convertDataToHexStr:[iv dataUsingEncoding:NSUTF8StringEncoding]];//向量二进制数据转16进制字符串
            NSString * two = [self convertDataToHexStr:data];//加密后的二进制转16进制字符串
//            NSString * one =[self base64Encode:[iv dataUsingEncoding:NSUTF8StringEncoding]];//向量二进制数据转16进制字符串
//            NSString * two = [self base64Encode:data];//加密后的二进制转16进制字符串
//            [ciphertext appendString:one];//拼接向量(根据后台需求 可能固定的向量就不用拼接)
            [ciphertext appendString:two];//拼接加密后的数据
            [ciphertext lowercaseString];//转小写   以上都是根据服务端需求来写,有些可能不是转16进制，可能是base64，可以用GTMBase库，github上搜一下就行。
      }
      return [ciphertext copy];//返回最后字符串 传给后台
}

//将NSString转换成十六进制的字符串则可使用如下方式:
- (NSString *)convertDataToHexStr:(NSData *)data
{
     NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];

    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    return string;
}

// data 2 base64
- (NSString*) base64Encode:(NSData *)data
{
    static char base64EncodingTable[64] = {
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
        'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
        'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
    };
    int length = [data length];
    unsigned long ixtext, lentext;
    long ctremaining;
    unsigned char input[3], output[4];
    short i, charsonline = 0, ctcopy;
    const unsigned char *raw;
    NSMutableString *result;
    
    lentext = [data length];
    if (lentext < 1)
        return @"";
    result = [NSMutableString stringWithCapacity: lentext];
    raw = [data bytes];
    ixtext = 0;
    
    while (true) {
        ctremaining = lentext - ixtext;
        if (ctremaining <= 0)
            break;
        for (i = 0; i < 3; i++) {
            unsigned long ix = ixtext + i;
            if (ix < lentext)
                input[i] = raw[ix];
            else
                input[i] = 0;
        }
        output[0] = (input[0] & 0xFC) >> 2;
        output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);
        output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);
        output[3] = input[2] & 0x3F;
        ctcopy = 4;
        switch (ctremaining) {
            case 1:
                ctcopy = 2;
                break;
            case 2:
                ctcopy = 3;
                break;
        }
        
        for (i = 0; i < ctcopy; i++)
            [result appendString: [NSString stringWithFormat: @"%c", base64EncodingTable[output[i]]]];
        
        for (i = ctcopy; i < 4; i++)
            [result appendString: @"="];
        
        ixtext += 3;
        charsonline += 4;
        
        if ((length > 0) && (charsonline >= length))
            charsonline = 0;
    }
    return result;
}

//获取当前时间戳
- (NSString *)currentTimeStr{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

- (void)observeNetWork {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusNotReachable || status == AFNetworkReachabilityStatusUnknown) {
            //无网络链接
            NSLog(@"==无网络链接");
        } else {
            //网络链接成功
//            if (_menuList.count == 0) {
            [self requestData];
//            }
            NSLog(@"==网络链接成功");
        }
    }];
}

- (void)requestData
{
    [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypeGet URLString:@"index" parameters:@{} done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        self.commendList = responseObject[@"data"][@"commend_list"];
        self.yingxiangList = responseObject[@"data"][@"yingxiang_list"];
        self.vipList = responseObject[@"data"][@"vip_list"];
        self.menuList = responseObject[@"data"][@"nav_list"];
        [self.magicView reloadData];
        
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}

- (void)setupUI
{
    self.magicView.itemScale = 1.2;
    self.magicView.navigationHeight = 52;
//    self.magicView.headerHidden = NO;
//    self.magicView.headerHeight = 40;
    self.magicView.sliderStyle = VTSliderStyleBubble;
    self.magicView.againstStatusBar = YES;
    self.magicView.headerView.backgroundColor = UIColor.whiteColor;
    self.magicView.navigationColor = [UIColor whiteColor];
    self.magicView.bubbleInset = UIEdgeInsetsMake(4, 10, 4, 10);
    
//    self.magicView.bubbleRadius = 10;
    self.magicView.sliderColor = RGB_VALUE(0xDC0000);
    self.magicView.separatorHeight = 0.f;
    self.edgesForExtendedLayout = UIRectEdgeAll;
}

#pragma mark - VTMagicViewDataSource
- (NSArray<NSString *> *)menuTitlesForMagicView:(VTMagicView *)magicView {
    NSMutableArray *titleList = [NSMutableArray array];
    for (NSDictionary *menu in _menuList) {
        [titleList addObject:menu[@"title"]];
    }
    return titleList;
}

- (UIButton *)magicView:(VTMagicView *)magicView menuItemAtIndex:(NSUInteger)itemIndex {
    static NSString *itemIdentifier = @"itemIdentifier";
    UIButton *menuItem = [magicView dequeueReusableItemWithIdentifier:itemIdentifier];
    if (!menuItem) {
        menuItem = [UIButton buttonWithType:UIButtonTypeCustom];
        [menuItem setTitleColor:RGB_VALUE(0x646464) forState:UIControlStateNormal];
        [menuItem setTitleColor:RGB_VALUE(0xFFFFFF) forState:UIControlStateSelected];
        menuItem.titleLabel.font = JSS_MEDIUM_FONT_6;
    }
    // 默认会自动完成赋值
//    MenuInfo *menuInfo = _menuList[itemIndex];
//    [menuItem setTitle:menuInfo.title forState:UIControlStateNormal];
    return menuItem;
}

- (UIViewController *)magicView:(VTMagicView *)magicView viewControllerAtPage:(NSUInteger)pageIndex {
    if (0 == pageIndex) {
        static NSString *recomId = @"recom.identifier";
        HomeRecommandViewController *ViewController = [magicView dequeueReusablePageWithIdentifier:recomId];
        if (!ViewController) {
            ViewController = [[HomeRecommandViewController alloc] init];
        }
        ViewController.commendList = self.commendList;
        ViewController.yingxiangList = self.yingxiangList;
        ViewController.vipList = self.vipList;
        return ViewController;
    }
//
    static NSString *gridId = @"grid.identifier";
    HomeCategoryViewController *viewController = [magicView dequeueReusablePageWithIdentifier:gridId];
    if (!viewController) {
        viewController = [[HomeCategoryViewController alloc] init];
    }
    return viewController;
}

#pragma mark - VTMagicViewDelegate
- (void)magicView:(VTMagicView *)magicView viewDidAppear:(__kindof UIViewController *)viewController atPage:(NSUInteger)pageIndex {
//    NSLog(@"index:%ld viewDidAppear:%@", (long)pageIndex, viewController.view);
}

- (void)magicView:(VTMagicView *)magicView viewDidDisappear:(__kindof UIViewController *)viewController atPage:(NSUInteger)pageIndex {
//    NSLog(@"index:%ld viewDidDisappear:%@", (long)pageIndex, viewController.view);
}

- (void)magicView:(VTMagicView *)magicView didSelectItemAtIndex:(NSUInteger)itemIndex {
//    NSLog(@"didSelectItemAtIndex:%ld", (long)itemIndex);
}

@end
